//package com.zhongli.devplatform.controller;
//
//import com.alibaba.fastjson.JSONObject;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.zhongli.devplatform.bean.Res;
//import com.zhongli.devplatform.component.JwtTokenUtil;
//import com.zhongli.devplatform.component.qq.QQAuthUtil;
//import com.zhongli.devplatform.component.qq.QQClientConfig;
//import com.zhongli.devplatform.component.wx.WeChatAuthUtil;
//import com.zhongli.devplatform.constant.Consts;
//import com.zhongli.devplatform.dto.UserBindDTO;
//import com.zhongli.devplatform.po.user.ReadUserPO;
//import com.zhongli.devplatform.security.qq.QQAccessToken;
//import com.zhongli.devplatform.security.qq.QQUserInfo;
//import com.zhongli.devplatform.security.weixin.WeixinAuthenticationToken;
//import com.zhongli.devplatform.service.imp.user.ReadUserService;
//import com.zhongli.devplatform.service.imp.user.UserRegisterService;
//import io.swagger.annotations.ApiImplicitParam;
//import io.swagger.annotations.ApiImplicitParams;
//import io.swagger.annotations.ApiModelProperty;
//import io.swagger.annotations.ApiOperation;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.BadCredentialsException;
//import org.springframework.security.authentication.DisabledException;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UserDetailsService;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.concurrent.TimeUnit;
//
//@RestController
//@RequestMapping("/auth")
//@Slf4j
//public class UserAuthenticationController_bak {
//
//    @Autowired
//    private WeChatAuthUtil weChatAuthUtil;
//
//    @Autowired
//    private AuthenticationManager authenticationManager;
//
//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;
//
//    @Autowired
//    private UserDetailsService userDetailsService;
//
//    @Autowired
//    private ReadUserService userService;
//
//    @Value("${token.expirationMilliSeconds}")
//    private long expirationMilliSeconds;
//
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;
//
//    @Autowired
//    private UserRegisterService userRegisterService;
//
//    @Autowired
//    private QQClientConfig clientConfig;
//
//    @Autowired
//    private QQAuthUtil authUtil;
//
//    /**
//     * 微信授权登录
//     * code获取用户openid
//     * @param code
//     * @author WuXiCheng
//     * @return
//     * @throws Exception
//     */
//    @ApiOperation(value = "微信授权登录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "code", value = "用户换取access_token的code，仅在ErrCode为0时有效", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "role", value = "用户第三方登录需要选择的角色（student学生,parent老师）",required = true,dataType = "String")
//    })
//    @PostMapping("/wx/login")
//    public Res weChatLogin(@RequestParam("code") String code,@RequestParam("role") String role) throws Exception {
//        String openid;
//        String token;
//        try {
//            //通过code获取微信授权信息
//            String url = weChatAuthUtil.getAuthUrl(code);
//            //发送微信认证请求
//            JSONObject jsonObject = WeChatAuthUtil.doGetJson(url);
//            openid = jsonObject.getString("openid");
//            token = jsonObject.getString("access_token");
//            String infoUrl = weChatAuthUtil.getUserInfoUrl(token,openid);
//            //获取微信用户信息
//            JSONObject wxUserInfo = WeChatAuthUtil.doGetJson(infoUrl);
//            if (wxUserInfo != null && openid != null) {
//                //注册微信用户
//                userRegisterService.wxRegister(wxUserInfo,role);
//            } else {
//                return Res.not_ok("登录失败");
//            }
//        } catch (Exception e) {
//            log.error("微信登录失败【" + e.getMessage() + "】");
//            return Res.not_ok("登录失败");
//        }
//        //认证微信用户
//        authenticate(openid);
//        String accountNum = userService.getOne(new QueryWrapper<ReadUserPO>().select("account_num").eq("weixin_id", openid)).getAccountNum();
//        final UserDetails userDetails = userDetailsService
//                .loadUserByUsername(accountNum);
//        //生成jwtToken
//        final String jwtToken = jwtTokenUtil.generateToken(userDetails);
//        //放入token到redis
//        String key = Consts.USER_TOKEN + userDetails.getUsername();
//        stringRedisTemplate.opsForValue().set(key,token, expirationMilliSeconds, TimeUnit.MILLISECONDS);
//        return  new Res<>(0,"登录成功", jwtToken);
//    }
//
//    /**
//     * 通过code，qq登录认证
//     * @param code
//     * @return
//     * @throws Exception
//     */
//    @ApiModelProperty("QQ登录认证")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "code", value = "用户换取access_token的code，仅在ErrCode为0时有效", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "role", value = "用户第三方登录需要选择的角色（student学生,parent老师）",required = true,dataType = "String")
//    })
//    @PostMapping("/qq/login")
//    public Res qqLogin(@RequestParam("code") String code,@RequestParam("role") String role) throws Exception {
//        QQAccessToken qqAccessToken;
//        String openId = "";
//        try {
//            //拼接获取tokenUrl
//            String tokenAccessApi = String.format(clientConfig.getToken_access_api(),
//                    clientConfig.getAccessTokenUri(),
//                    clientConfig.getGrantType(),
//                    clientConfig.getAppId(),
//                    clientConfig.getSecret(), code,
//                    clientConfig.getRedirectUri());
//            //获取accessToken
//            qqAccessToken = authUtil.getToken(tokenAccessApi);
//            openId = authUtil.getOpenId(qqAccessToken.getAccessToken());
//            //获取qq用户信息
//            QQUserInfo qqUserInfo = authUtil.getUserInfo(qqAccessToken.getAccessToken(), openId);
//            qqUserInfo.setOpenId(openId);
//            userRegisterService.qqRegister(qqUserInfo,role);
//        } catch (Exception e) {
//            log.error("QQ登录失败【" + e.getMessage() + "】");
//        }
//        //认证已注册的qq用户
//        authenticate(openId);
//
//        String userName = userService.getOne(new QueryWrapper<ReadUserPO>().eq("qq_id", openId)).getAccountNum();
//        final UserDetails userDetails = userDetailsService
//                .loadUserByUsername(userName);
//        //封装redis集合
//        String key = Consts.USER_TOKEN + userDetails.getUsername();
//        //获取token
//        final String jwtToken = jwtTokenUtil.generateToken(userDetails);
//        //放入redis
//        stringRedisTemplate.opsForValue().set(key,jwtToken, expirationMilliSeconds, TimeUnit.MILLISECONDS);
//
//        return new Res<>(0,"登录成功",jwtToken);
//    }
//
//    /**
//     * 用户绑定
//     * @param userBindDTO
//     * @return
//     */
//    @ApiOperation(value = "用户绑定")
//    @PostMapping("/bindWxUser")
//    private Res bindWxUser(@RequestBody UserBindDTO userBindDTO){
//        return userRegisterService.bindUser(userBindDTO);
//    }
//
//    /**
//     * 获取微信用户信息
//     * @param accessToken
//     * @param openId
//     * @return
//     */
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "accessToken", value = "微信认证过后的accessToken", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "openId", value = "微信用户唯一openId",required = true,dataType = "String")
//    })
//    @ApiOperation(value = "获取微信用户信息")
//    @GetMapping("/wx/getUserInfo")
//    public Res getUserInfo(@RequestParam("accessToken") String accessToken,@RequestParam("openId") String openId){
//        return userRegisterService.getWxUserInfo(accessToken,openId);
//    }
//
//    /**
//     * Security认证
//     * @param openId
//     * @throws Exception
//     */
//    private void authenticate(String openId) throws Exception {
//        try {
//            authenticationManager.authenticate(new WeixinAuthenticationToken(openId));
//        } catch (DisabledException e) {
//            throw new Exception("USER_DISABLED", e);
//        } catch (BadCredentialsException e) {
//            throw new Exception("INVALID_CREDENTIALS", e);
//        }
//    }
//}
